/**
 * Created Date: Monday, July 24th 2023, 11:52:36 pm
 * Author: CodingGorit
 * -----
 * Last Modified: Tue Jul 25 2023
 * Modified By: CodingGorit
 * -----
 * Copyright © 2019 —— 2023 fmin-courses TP Center All Rights Reserved
 * ------------------------------------
 * Javascript will save your soul!
 */


import { Request, Response, NextFunction } from 'express';
import { Result } from '../common/Result';
import OssManager from "../manager/OssManager";
import { ResultCodeEnum, ResultMessageEnum } from "../enums/ResultEmums";
import log from "../utils/log";
import { IUploadCallback } from '../types';
import fs from 'fs';

const TAG = "FileService";

/**
 * 上传文件到七牛云 oss
 * @param req Request
 * @param res Response
 * @returns 
 */
export const uploadFileByQiuniuOSS = (req: Request, res: Response)=> {
    if (!req.file) {
        res.send("<h3>file 内容为空</h3>");
    } else {
        const fileName = req.file.filename;
        const path = req.file.path;
        log.info(`${TAG}, ${JSON.stringify(req.file)}`);
        OssManager.getInstance().uploadFileWithLocal(fileName, path , (result: IUploadCallback) => {
            log.info(`${TAG} result => ${JSON.stringify(result)}`);
            const succed = result.state === "success";

            if (succed) {
                deleteFile(path);
            }
            let resp = {
                code : succed ? ResultCodeEnum.UPLOAD_SUCCESS : ResultCodeEnum.UPLOAD_FAILED,
                msg: succed ? ResultMessageEnum.UPLOAD_SUCCESS : ResultMessageEnum.UPLOAD_FAILED,
                data: result.data
            }
            res.send(resp);
        })
    }
};

const deleteFile = (path: string) => {
    if (fs.existsSync(path)) {
        fs.rmSync(path);
    }
}